/*
 * Copyright (c) 2021 Zsj. All rights reserved.
 */

package com.jzz.crawlerweb.handler.config;

import com.jzz.crawlerweb.handler.props.CaptchaProps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;

/**
 * 注销拦截器，负责处理注销请求
 */
public class LogoutInterceptor implements HandlerInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(LogoutInterceptor.class);

    private final CaptchaProps captchaProps;

    public LogoutInterceptor(CaptchaProps captchaProps) {
        this.captchaProps = captchaProps;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        logger.info("Handle logout request [{}]", session.getId());

        if (session.getAttribute("success") == null) {
            response.setStatus(401);
            response.setContentType("application/json; charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.write("{\"code\": -1, \"message\": \"用户未登录\"}");
            writer.flush();
            writer.close();
            return false;
        } else {
            session.removeAttribute("success");
            session.removeAttribute("secret");
        }
        return true;
    }
}
